package com.youlu.campus.web.config.filter;

import com.youlu.campus.base.exception.BusinessException;
import com.youlu.campus.common.constants.RequestHeaderConstant;
import com.youlu.campus.common.enums.PlatformEnum;
import com.youlu.campus.service.wechat.WechatConfigInfoService;
import com.youlu.campus.web.config.filter.utils.ResponseUtils;
import com.yuelin.infrastructure.quantum.common.QResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 请求头Filter
 *
 * @Description: CheckAppIdFilter
 * @Date 2025/8/11
 * @module CheckAppIdFilter
 * @author: su
 */
@Slf4j
public class RequestHeaderFilter extends OncePerRequestFilter {

    private static final List<String> FILTER_PLATFORM = Arrays.asList(PlatformEnum.WECHAT_H5.getValue(), PlatformEnum.QQ_H5.getValue());


    private final String prefix;

    private final WechatConfigInfoService wechatConfigInfoService;

    public RequestHeaderFilter(String prefix, WechatConfigInfoService wechatConfigInfoService) {
        this.prefix = prefix;
        this.wechatConfigInfoService = wechatConfigInfoService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String appId = request.getHeader(RequestHeaderConstant.APP_ID);
        String platform = request.getHeader(RequestHeaderConstant.PLATFORM);
        log.info("filter appId:{},platform:{}", appId, platform);
        if (StringUtils.isAnyBlank(appId, platform)) {
            log.error("appId is null");
            ResponseUtils.writeOutJson(response, QResult.fail("网络异常,请联系管理员"));
            return;
        }
        if (!FILTER_PLATFORM.contains(platform)) {
            filterChain.doFilter(request, response);
            return;
        }
        if (PlatformEnum.WECHAT_H5.getValue().equals(platform)) {
            try {
                wechatConfigInfoService.find(appId);
            } catch (BusinessException e) {
                ResponseUtils.writeOutJson(response, QResult.fail(e.getMessage()));
                return;
            }
        }
        if (PlatformEnum.QQ_H5.getValue().equals(platform)) {
            if (!appId.equals("101950655")) {
                ResponseUtils.writeOutJson(response, QResult.fail("请使用微信环境打开!"));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

}
